import React, { Component } from 'react';
import {connect} from 'react-redux'
import { reqRoleList, reqAddRole,reqUpdateRoleRight } from '../../api/index'

import { Button, Card, Table, Modal, Form, Input, message,Tree } from 'antd';
import { PlusCircleOutlined } from '@ant-design/icons';
import { SpaceContext } from 'antd/lib/space';
import DefaultConfig from '../../userConfig/userconfig'
import {TimeChange} from '../../utils/timeChange'


class Roles extends Component {
    state = {
        roleList: [],
        isModalVisible: false,
        isChange:false,
        isCheck:true,//标识用户是否选中，用来启用和禁用修改按钮
        currID:'',//当前选中role的id
        name:'',//当前选中用户的名字
        checkedKeys:[],//当前用户已经有的权限

    }
    getRoleList = async () => {
        let list = await reqRoleList()
        if (list.data.status === 0) {
            console.log(list.data.data)
            //将时间戳修改为时间
            let temp = list.data.data.map((item)=>{
                //原有的属性不变，将时间覆盖
                //先要看当前的数据有没有auth_time
                if(item.auth_time){//有
                    console.log(item)
                    return {...item,create_time:TimeChange(item.create_time),auth_time:TimeChange(item.auth_time)}
                }else{
                    return {...item,create_time:TimeChange(item.create_time)}
                }
                
            })
            this.setState({ roleList: temp })
        }
    }
    addRole = () => {
        this.setState({ isModalVisible: true })
    }

    onCancel = () => {
        this.setState({ isModalVisible: false })
    }
    onFinish = async(values)=>{
        //console.log("这是我的values",values)
        //发送请求创建角色
        let result = await reqAddRole({roleName:values.username})
        if(result.data.status===0){
            //成功
            this.setState({isModalVisible: false})
            //成功之后重新请求最新的数据
            this.getRoleList()
        }else{
            message.error("添加失败请重试")
        }
    }
    onChange = (selectedRowKeys, selectedRows)=>{
        this.setState({isCheck:false,currID:selectedRowKeys[0],name:selectedRows[0].name})
        if(selectedRows[0].menus){
            this.setState({checkedKeys:selectedRows[0].menus})
        }
        console.log("这时我的",selectedRows)
    }
    changeRight = ()=>{
        this.setState({isChange:true})
    }
    //checkedKeys, e:{checked: bool,
    onCheck = (checkedKeys,)=>{
        this.setState({checkedKeys})
        console.log(checkedKeys)
    }
    pushRight = async()=>{
        const {currID,checkedKeys} = this.state
        const author_p = this.props.user.username
        const date = +new Date()
        //console.log(date)
        console.log(currID,checkedKeys,date,author_p)
        //发送请求提交数据
        let result = await reqUpdateRoleRight(currID,checkedKeys,date,author_p)
        if(result.data.status===0){
            message.success("权限修改成功")
            this.setState({isChange:false})
        }else{
            message.error("网络不好，请重试")
        }

    }
    componentWillMount() {
        console.log("component will")
    
        this.treeData = DefaultConfig
          
        this.columns = [
            {
                title: '角色名称',
                dataIndex: 'name',
                key: 'name',
                width: '15%'
            },
            {
                title: '创建时间',
                dataIndex: 'create_time',
                key: 'create_time',
                width: '30%'
            },
            {
                title: '授权时间',
                dataIndex: 'auth_time',
                key: 'auth_time',
                width: '30%'
            },
            {
                title: '授权人',
                dataIndex: 'auth_name',
                key: 'auth_name',
                width: '15%'
            },
        ];
    }
    componentDidMount() {
        console.log("componentDid")
        //请求角色列表
        this.getRoleList()
    }
    render() {
        console.log("render 我执行了一遍")
        const { isModalVisible,roleList,isCheck ,isChange,name,checkedKeys} = this.state
        return (
            <Card
                title={
                    <span>
                        <Button type="primary" onClick={this.addRole}>创建角色</Button>&nbsp;&nbsp;
                        <Button type="primary" disabled={isCheck} onClick={this.changeRight}>修改角色权限</Button>
                    </span>
                }
            >
                <Table
                    dataSource={roleList}
                    columns={this.columns}
                    bordered
                    //必须要指定这个不然会出现全部选中的bug
                    rowKey='_id'
                    pagination={{ pageSize: 5, total: this.state.roleList.length, showQuickJumper: true, showSizeChanger: false }}
                    rowSelection={{ columnTitle: "当前选中", type: 'radio' ,onChange:this.onChange}}
                // 这里指定一下current，不然有页面显示bug
                //pagination={current:this.state.pageNum,defaultCurrent:1,pageSize:5,total:this.props.ProduceList.total,showQuickJumper:true, showSizeChanger:false,onChange:this.PageChange}} 
                />
                <Modal title="添加用户" visible={isModalVisible} footer={null} onCancel={this.onCancel}>
                    <Form
                        name="basic"
                        initialValues={{ remember: true }}
                        onFinish={this.onFinish}
                    >
                        <Form.Item
                            label="Username"
                            name="username"
                            rules={[{ required: true, message: 'Please input your username!' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item >
                            <Button type="primary" htmlType="submit">
                                Submit
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal title="修改权限" visible={isChange} onCancel={()=>this.setState({isChange:false})}onOk={this.pushRight}>
                    <Input value={name} disabled={true}/>
                    <Tree
                    //selectedKeys = {checkedKeys}
                    style={{marginTop:20}}
                    checkable
                    onSelect={this.onSelect}
                    onCheck={this.onCheck}
                    treeData={this.treeData}
                  />
                </Modal>
                </Card>
        )
    }
}
export default connect(
    state=>({user:state.user})
)(Roles)